<template>
	<a-drawer :title="title" :maskClosable="true" :width="drawerWidth" placement="right" :closable="true" @close="handleCancel"
	:visible="visible" style="height: 100%;overflow: auto;padding-bottom: 53px;">

		<template slot="title">
			<div style="width: 100%;">
				<span>{{ title }}</span>
				<span style="display:inline-block;width:calc(100% - 51px);padding-right:10px;text-align: right">
					<a-button @click="toggleScreen" icon="appstore" style="height:20px;width:20px;border:0px"></a-button>
				</span>
			</div>

		</template>

		<a-spin :spinning="confirmLoading">
			<a-form :form="form">

				<a-form-item label="任务名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
					<a-input placeholder="请输入任务名称" v-decorator.trim="[ 'name', validatorRules.name]" :readOnly="title != '编辑'" />
				</a-form-item>

        <a-form-item label="摄像机编码" :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="false">
          <a-input placeholder="请输入摄像机编码" v-decorator.trim="['cameraId']" />
        </a-form-item>

        <a-form-item label="摄像机名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入摄像机名称" v-decorator.trim="[ 'cameraName']" :readOnly="true" />
        </a-form-item>

        <a-form-item label="任务类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-radio-group v-decorator.trim="['typeId', validatorRules.typeId]" button-style="solid">
            <a-radio-button value="0">
              单次
            </a-radio-button>
            <a-radio-button value="4">
              长期
            </a-radio-button>
            <!--                      <a-radio-button value="3">-->
            <!--                        月-->
            <!--                      </a-radio-button>-->
            <!--                      <a-radio-button value="2">-->
            <!--                        周-->
            <!--                      </a-radio-button>-->
            <!--                      <a-radio-button value="1">-->
            <!--                        日-->
            <!--                      </a-radio-button>-->
          </a-radio-group>
        </a-form-item>
        <a-form-item  v-if="form.getFieldValue('typeId') == 0" label="开始时间点" :labelCol="labelCol"
                      :wrapperCol="wrapperCol">
          <a-range-picker
              size="small"
              :show-time="{ format: 'HH:mm:ss' }"
              format="YYYY-MM-DD HH:mm:ss"
              :placeholder="['开始时间', '结束时间']"
              :disabled-date="disabledDate"
              v-decorator="['rangeValue', validatorRules.rangeValue]"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="任务描述">
          <a-textarea placeholder="任务描述" v-decorator.trim="[ 'taskDesc']"/>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="启用状态" name="启用状态">
          <a-switch
              v-decorator.trim="['used', {rules: [{required: true, message: '请输入选择'}],valuePropName: 'checked'}]"/>
        </a-form-item>
			</a-form>
		</a-spin>

		<div class="drawer-bootom-button" v-show="!disableSubmit">
			<a-popconfirm title="确定放弃编辑？" @confirm="handleCancel" okText="确定" cancelText="取消">
				<a-button style="margin-right: .8rem">取消</a-button>
			</a-popconfirm>
			<a-button @click="handleSubmit" type="primary" :loading="confirmLoading">提交</a-button>
		</div>
	</a-drawer>
</template>

<script>
	import pick from 'lodash.pick'
	import {
		getAction
	} from '@/api/manage'
	import moment from 'moment'
	import {
    modifyRecordTask,
	} from '@/api/api'
	import {
		disabledAuthFilter
	} from "@/utils/authFilter"
	import JImageUpload from '../../../components/jeecg/JImageUpload'

	export default {
		name: "UserModal",
		components: {
			JImageUpload,
		},
		data() {
			return {
				departDisabled: false, //是否是我的部门调用该页面
				roleDisabled: false, //是否是角色维护调用该页面
				modalWidth: 800,
				drawerWidth: 700,
				modaltoggleFlag: true,
				confirmDirty: false,
				taskId: "", //保存任务id
				disableSubmit: false,
				validatorRules: {
					name: {
						rules: [{
							required: true,
							message: '请输入任务名称!'
						}]
					},
          rangeValue: {
            rules: [{
              required: true,
              message: '请选择录像时间段!'
            }]
          },
          typeId: {
						rules: [{
							required: true,
							message: '请选择任务类型!'
						}]
					},
				},
				title: "操作",
				visible: false,
				model: {},
				roleList: [],
				labelCol: {
					xs: {
						span: 24
					},
					sm: {
						span: 5
					},
				},
				wrapperCol: {
					xs: {
						span: 24
					},
					sm: {
						span: 16
					},
				},
				uploadLoading: false,
				confirmLoading: false,
				form: this.$form.createForm(this),
				currentTenant: [],
				treeData: []
			}
		},
		created() {
      this.form.getFieldDecorator('rangeValue', {initialValue: [], preserve: true})

    },
		computed: {

		},
		methods: {
			isDisabledAuth(code) {
				return disabledAuthFilter(code);
			},
			//窗口最大化切换
			toggleScreen() {
				if (this.modaltoggleFlag) {
					this.modalWidth = window.innerWidth;
				} else {
					this.modalWidth = 800;
				}
				this.modaltoggleFlag = !this.modaltoggleFlag;
			},
			refresh() {
				this.taskId = ""
				this.departId = [];
				this.currentTenant = []
			},
			add() {

			},
			edit(record) {
				console.log(record)
				let that = this;
				if (record.taskId) {
					getAction("/record/info/" + record.taskId).then((res) => {
						if (res.code == "00000") {
							this.resetScreenSize(); // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
							that.form.resetFields();
							that.taskId = res.data.taskId;
							that.visible = true;
							that.model = Object.assign({}, res.data);
              that.model.rangeValue = [];

              that.model.rangeValue.push(moment(res.data.startDateTime, 'YYYY-MM-DD HH:mm:ss'));

              if (res.data.endDateTime) {
                that.model.rangeValue.push(moment(res.data.endDateTime, 'YYYY-MM-DD HH:mm:ss'))
              } else {
                that.model.rangeValue.push(moment(res.data.startDateTime, 'YYYY-MM-DD HH:mm:ss'));
              }

							console.log("that.model.rangeValue", that.model.rangeValue);

							that.$nextTick(() => {
                that.form.setFieldsValue({
                  'used': that.model.used == "1" ? true : false
                });
								that.form.setFieldsValue(pick(that.model, 'name', 'typeId', 'rangeValue', 'taskDesc', 'cameraId', 'cameraName'))
							});
						} else {
							that.$message.warning("查询失败");
						}
					})
				} else {
					this.resetScreenSize(); // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
					this.form.resetFields();
					this.userId = record.userId;
					this.visible = true;
					this.model = Object.assign({}, record);
					this.$nextTick(() => {
            that.form.setFieldsValue(pick(that.model, 'name', 'typeId', 'rangeValue', 'taskDesc', 'cameraId', 'cameraName'))
					});
				}
			},

			close() {
				this.$emit('close');
				this.visible = false;
				this.disableSubmit = false;
			},
			moment,
			handleSubmit() {
				const that = this;
				// 触发表单验证
				this.form.validateFields((err, values) => {
					if (!err) {
						that.confirmLoading = true;
						let formData = Object.assign(this.model, values);
						formData.startDateTime = values['rangeValue'][0].format('YYYY-MM-DD HH:mm:ss');
            formData.endDateTime = values['rangeValue'][1].format('YYYY-MM-DD HH:mm:ss');
            formData.used = values['used'] ? "1" : "0";
            console.log(formData)
            let obj = modifyRecordTask(formData)
						obj.then((res) => {
							if (res.code == "00000") {
								that.$message.success("操作成功");
								that.$emit('ok');
							} else {
								that.$message.warning("操作失败" + res.msg);
							}
						}).finally(() => {
							that.confirmLoading = false;
							that.close();
						})

					}
				})
			},
			handleCancel() {
				this.close()
			},
			validateToNextPassword(rule, value, callback) {
				const form = this.form;
				const confirmpassword = form.getFieldValue('confirmpassword');

				if (value && confirmpassword && value !== confirmpassword) {
					callback('两次输入的密码不一样！');
				}
				if (value && this.confirmDirty) {
					form.validateFields(['confirm'], {
						force: true
					})
				}
				callback();
			},
			compareToFirstPassword(rule, value, callback) {
				const form = this.form;
				if (value && value !== form.getFieldValue('password')) {
					callback('两次输入的密码不一样！');
				} else {
					callback()
				}
			},
			validatePhone(rule, value, callback) {
				if (!value) {
					callback("请输入手机号码!")
				} else {
					//update-begin--Author:kangxiaolin  Date:20190826 for：[05] 手机号不支持199号码段--------------------
					if (new RegExp(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/).test(value)) {
						//update-end--Author:kangxiaolin  Date:20190826 for：[05] 手机号不支持199号码段--------------------
						callback()
					} else {
						callback("请输入正确格式的手机号码!");
					}
				}
			},
			validateEmail(rule, value, callback) {
				if (!value) {
					callback()
				} else {
					if (new RegExp(
							/^(([^<>()\]\\.,;:\s@"]+(\.[^<>()\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
						).test(value)) {
						callback()
					} else {
						callback("请输入正确格式的邮箱!")
					}
				}
			},
			handleConfirmBlur(e) {
				const value = e.target.value;
				this.confirmDirty = this.confirmDirty || !!value
			},
			// handleChange(info) {
			// 	this.picUrl = "";
			// 	if (info.file.status === 'uploading') {
			// 		this.uploadLoading = true;
			// 		return
			// 	}
			// 	if (info.file.status === 'done') {
			// 		var response = info.file.response;
			// 		this.uploadLoading = false;
			// 		console.log(response);
			// 		if (response.success) {
			// 			this.model.avatar = response.message;
			// 			this.picUrl = "Has no pic url yet";
			// 		} else {
			// 			this.$message.warning(response.message);
			// 		}
			// 	}
			// },
			// 根据屏幕变化,设置抽屉尺寸
			resetScreenSize() {
				let screenWidth = document.body.clientWidth;
				if (screenWidth < 500) {
					this.drawerWidth = screenWidth;
				} else {
					this.drawerWidth = 700;
				}
			},
      disabledDate(current) {
        // 限制只能选今天及之后的日期（今天可选中）
        return current && current < moment().subtract(1, 'days').endOf('day')
      },
		}
	}
</script>

<style scoped>
	.avatar-uploader>.ant-upload {
		width: 104px;
		height: 104px;
	}

	.ant-upload-select-picture-card i {
		font-size: 49px;
		color: #999;
	}

	.ant-upload-select-picture-card .ant-upload-text {
		margin-top: 8px;
		color: #666;
	}

	.ant-table-tbody .ant-table-row td {
		padding-top: 10px;
		padding-bottom: 10px;
	}

	.drawer-bootom-button {
		position: absolute;
		bottom: -8px;
		width: 100%;
		border-top: 1px solid #e8e8e8;
		padding: 10px 16px;
		text-align: right;
		left: 0;
		background: #fff;
		border-radius: 0 0 2px 2px;
	}
</style>
